"use client";
import React, {useState} from "react";
import {Button, Group, Modal, Stack, TextInput} from "@mantine/core";
import {IconPlus} from "@tabler/icons-react";
import {useDisclosure} from "@mantine/hooks";
import {useForm} from "@mantine/form";
import {AddProjectProps} from "./interface";

const MODALS_RADIUS = "md";

function AddProject() {
  // [1] 易用性：按钮的loading状态（VPN访问时网络不佳，loading做到前端防抖，增强用户体验）
  const [loading, setLoading] = useState(false);

  // [2] 核心功能：表单收集
  const form = useForm<AddProjectProps>({
    mode: "uncontrolled",
    initialValues: {
      version: "",
      name: "",
    },
    validate: {},
  });
  return (
    <form
      onSubmit={form.onSubmit((values) => {
        setLoading(true);
      })}
    >
      <Stack>
        <TextInput
          withAsterisk // 由于是新建表单，所以要有必填项标识
          label="方案版本"
          placeholder="请输入方案版本"
          radius={MODALS_RADIUS}
          key={form.key("version")} // 操作的锚点
          {...form.getInputProps("version")}
        />
        <TextInput
          withAsterisk // 由于是新建表单，所以要有必填项标识
          label="方案名称"
          placeholder="请输入方案名称"
          radius={MODALS_RADIUS}
          key={form.key("name")} // 操作的锚点
          {...form.getInputProps("name")}
        />
        <Group justify="flex-end">
          <Button type="submit" loading={loading} radius={MODALS_RADIUS}>
            确定
          </Button>
        </Group>
      </Stack>
    </form>
  );
}

export function ButtonAdd() {
  const [opened, {open, close}] = useDisclosure(false);
  return (
    <>
      <Button size="xs" leftSection={<IconPlus size={12} />} onClick={open}>
        新增
      </Button>
      <Modal title="新建方案" radius={MODALS_RADIUS} opened={opened} onClose={close}>
        <AddProject />
      </Modal>
    </>
  );
}
